package ar.uba.fi.taller2.ftrs.parser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class Pipe {
	
	// Tamaño del Pipe (normalmente 5)
	private int pipeSize=5;		
	
	// Strings del Pipe 
	private String[] pipe;	
	
	// Lista de locuciones conocidas para descartar
	private List<String> listaLocuciones;		
		
	public  Pipe( ){
		this.pipe = new String[this.pipeSize];
		this.listaLocuciones = new ArrayList<String>();		
		flushPipe();
	}
	
	public void flushPipe(){
		for (int i=0; i < this.pipeSize ; i++) this.pipe[i] = null;
	}
	
	public void setSize(int s){
		this.pipeSize = s;
	}
	
	public int getSize(){
		return this.pipeSize;
	}
	
	public void agregarLocucion(String s){
		if (!this.listaLocuciones.contains(s))
			this.listaLocuciones.add(s);
	}
	
	public void cargarLocuciones(String fileName) throws Exception{
		//Leo el Archivo
   	 	BufferedReader in = new BufferedReader(new FileReader(fileName));
   	 	if (!in.ready())
   	 		throw new IOException();
   	 	String line;	
   		while ( (line=in.readLine()) != null) {
			this.agregarLocucion(line);
		}		
	    in.close();
	}
	
	private void stringToPipe(String s){
		String str[] = s.split("[ ]+");
		int size = (str.length < this.pipeSize)?str.length:this.pipeSize;
		for (int i=0; i< this.pipeSize ; i++) this.pipe[i] = null;
		for (int i=0; i< size ; i++) this.pipe[i] = str[i];		
	}
	
	private String pipeToString(){
		String pipeString= new String("");
		for(int i= 0 ; i< this.pipeSize ; i++) pipeString+=this.pipe[i]+" ";
		return pipeString;
	}
	
	public String shift(String s){
		// Verifica si hay strings null en el pipe
		Boolean hasNulls = false;
		for(int i=0; i< ( this.pipeSize); i++)
			if ( this.pipe[i] == null ) 
				hasNulls=true;		
		if (hasNulls){
			// Inserta s en el primer null disponible
			int i=this.pipeSize-1;
			while( i >= 0 && this.pipe[i]==null ) i--;
			this.pipe[i+1]=s;
			return null;
			}else{
			// Realiza el shift de todas las palabras
			String returned = this.pipe[0];	
			for(int i=0; i< ( this.pipeSize-1); i++){
				pipe[i]=pipe[i+1];
				}	
			pipe[this.pipeSize -1 ] = s;
			return returned;
			}
	}
			
	public Boolean eliminarLocuciones(){
		String pipeString= this.pipeToString();
		for(int i= 0 ; i< this.listaLocuciones.size() ; i++) 
			if (pipeString.matches(".*"+(String)(this.listaLocuciones.get(i))+".*")){						
					String replaced = pipeString.replaceAll((String)this.listaLocuciones.get(i),"");
					this.stringToPipe(replaced);
				    return true;
				}
		return false;	
		}
			
}
